function OrderCtrl($scope, $http, $cookieStore) {
	$scope.addLicense = function() {
		$scope.editingOrder.licenses.push({});
	};
	
	$scope.removeLicense = function(license) {
		$scope.editingOrder.licenses.remove(license);
	};
	
	$scope.saveOrder = function() {
		$scope.orderForm.submited = true;
		
		if ($scope.orderForm.$invalid) {
			return false;
		}
		
		for ( var i = 0; i < $scope.editingOrder.licenses.length; i++) {
			var license = $scope.editingOrder.licenses[i];
			if (license.selectedDriver) {
				license.driverId = license.selectedDriver.originalObject.id;
			}
			license.orderId = $scope.editingOrder.id;
			license.saleDate = $scope.editingOrder.saleDate;
			license.years = $scope.editingOrder.years;
		}
		
		$http.post("/order/" + $scope.mode, $scope.editingOrder).success(function(response) {
			if (response.success) {
				$scope.backPage();
			} else {
				if (response.result == 101) {
					// 101: order name duplicated
					$scope.orderForm.name.$setValidity('duplicated', false);
				} else {
					$scope.orderForm.globalErrorMsg = response.message || "保存驱动失败！";
				}
			}
		});
	};
	
	$scope.backPage = function() {
		window.location.href = "/order/index?cookie=true";
	};
	
	$scope.init = function() {
		if (ORDER_ID) {
			$scope.mode = 'update';
		} else {
			$scope.mode = 'create';
		}
		
		if ($scope.mode == 'update') {
			$http.post("/order/get/" + ORDER_ID).success(function(response) {
				if(response.success) {
					$scope.editingOrder = response.data || {};
					$scope.editingOrder.licenses = $scope.editingOrder.licenses || [];
				} else {
					Message.error("错误", response.message || "加载数据失败！");
				}
			});
		} else {
			$scope.editingOrder = {};
			$scope.editingOrder.licenses = [];
			$scope.editingOrder.licenses.push({});
			
			$scope.$watch('editingOrder.id', function(newValue, oldValue) {
				$scope.orderForm.orderId.$setValidity('duplicated', true);
			});
		}
	};
 
	$scope.init();
};

app.controller('OrderCtrl', OrderCtrl);